import { _decorator, AnimationClip, Node, Animation, Button, Component, EventHandler, Sprite, SpriteFrame, UITransform, view, Widget, Label, math, director } from 'cc';
import { chunkArray, createUILabel, createUINode, getFrameAsset, loadAnimationClip, showToast } from '../utils';
import DataManager from '../Runtime/DataManager';
import ResourceManager from '../Runtime/ResourceManager';
import { GAME_MODE_ENUM } from '../../Enums';
const { ccclass } = _decorator;
import { userStore } from "../service/user"
import { LevelInfo } from '../types/type';
import { createRecord, updateRecord } from '../api/record';
@ccclass('CommonElement')
export class CommonElement extends Component {
    playGameNode: Node
    init() {
        this.setBackground()
        this.setLogo()
        // this.audioMute()
    }
    // 设置背景图
    async setBackground() {
        const node = createUINode("背景图片")
        node.setParent(this.node)
        let designSize = view.getVisibleSize()
        const transform = node.getComponent(UITransform)
        transform.setContentSize(designSize.width, designSize.height)
        const sprite = node.addComponent(Sprite)
        sprite.sizeMode = Sprite.SizeMode.CUSTOM
        let spriteFrames = await ResourceManager.Instance.loadDir("/assets/", SpriteFrame)
        sprite.spriteFrame = spriteFrames.find(item => item.name == "home-bg")
    }
    // 设置Logo
    async setLogo() {
        const node = createUINode("游戏Logo")
        node.setParent(this.node)
        // createUILabel({ parentNode: node, text: "神奇小妖精", fontSize: 120, lineHeight: 100, color: "#85BEF3" })
        const widget = node.addComponent(Widget)
        widget.isAlignTop = true
        widget.top = -270
    }
    // 开始游戏
    createPlayGame(content, manager = "homeManager") {
        const playGameNode = createUINode('playGameNode')
        playGameNode.setParent(content)
        this.playGameNode = playGameNode
        const widget = playGameNode.addComponent(Widget)
        widget.isAlignTop = true
        widget.top = 0
        widget.isAlignBottom = true
        widget.bottom = 0
        widget.isAlignLeft = true
        widget.left = 0
        widget.isAlignRight = true
        widget.right = 0
        const sprite = playGameNode.addComponent(Sprite)
        sprite.sizeMode = Sprite.SizeMode.CUSTOM
        sprite.spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, `${1290}.png`).spriteFrame
        let bluePerson = loadAnimationClip(DataManager.Instance.homeAssets, 'bluePerson', AnimationClip.WrapMode.Loop) // DataManager.Instance.homeBluePerson
        let greenPerson = loadAnimationClip(DataManager.Instance.homeAssets, 'greenPerson', AnimationClip.WrapMode.Loop)
        let bluePersonCilps = bluePerson.animation
        let greenPersonCilps = greenPerson.animation
        let singlePerson = createUINode("singlePerson")
        singlePerson.setParent(playGameNode)
        const singleSpriteNode = createUINode('personSpriteNode')
        singleSpriteNode.setParent(singlePerson)
        singleSpriteNode.setScale(2, 2)
        const singleSpriteWidget = singleSpriteNode.addComponent(Widget)
        singleSpriteWidget.isAlignTop = true
        singleSpriteWidget.top = 70
        const singleSprite = singleSpriteNode.addComponent(Sprite)
        singleSprite.spriteFrame = bluePerson.frame[0]
        const animation = singleSprite.addComponent(Animation)
        animation.defaultClip = bluePersonCilps
        animation.pause()
        let singleLabel = createUINode("personLabel")
        singleLabel.setParent(singlePerson)
        createUILabel({ parentNode: singleLabel, text: '单人', color: '#fbfbfd' })
        const singleWidget = singlePerson.addComponent(Widget)
        singleWidget.isAlignTop = true
        singleWidget.top = 0
        singleWidget.isAlignLeft = true
        singleWidget.left = 150


        let doublePerson = createUINode("doublePerson")
        doublePerson.setParent(playGameNode)
        let doubleLabel = createUINode("personLabel")
        doubleLabel.setParent(doublePerson)
        createUILabel({ parentNode: doubleLabel, text: '双人', color: '#fbfbfd' })
        const doubleWidget = doublePerson.addComponent(Widget)
        doubleWidget.isAlignTop = true
        doubleWidget.top = 0
        doubleWidget.isAlignRight = true
        doubleWidget.right = 150

        const doubleSpriteNode = createUINode('personSpriteNode')
        doubleSpriteNode.setParent(doublePerson)
        doubleSpriteNode.setScale(2, 2)
        const doubleSpriteWidget = doubleSpriteNode.addComponent(Widget)
        doubleSpriteWidget.isAlignTop = true
        doubleSpriteWidget.top = 70
        doubleSpriteWidget.isAlignLeft = true
        doubleSpriteWidget.left = -90
        const doubleSprite = doubleSpriteNode.addComponent(Sprite)
        doubleSprite.spriteFrame = bluePerson.frame[0]
        const doubleAnimation = doubleSprite.addComponent(Animation)
        doubleAnimation.defaultClip = bluePersonCilps
        doubleAnimation.pause()

        const doubleSpriteNode1 = createUINode('personSpriteNode1')
        doubleSpriteNode1.setParent(doublePerson)
        doubleSpriteNode1.setScale(2, 2)
        const doubleSprite1Widget = doubleSpriteNode1.addComponent(Widget)
        doubleSprite1Widget.isAlignTop = true
        doubleSprite1Widget.top = 70
        doubleSprite1Widget.isAlignLeft = true
        doubleSprite1Widget.left = 60
        const doubleSprite1 = doubleSpriteNode1.addComponent(Sprite)
        doubleSprite1.spriteFrame = greenPerson.frame[0]
        const doubleAnimation1 = doubleSprite1.addComponent(Animation)
        doubleAnimation1.defaultClip = greenPersonCilps
        doubleAnimation1.pause()

        let player1 = createUINode("player1")
        player1.setParent(content)
        createUILabel({ parentNode: player1, text: '电脑玩家1' })
        const player1Widget = player1.addComponent(Widget)
        player1Widget.isAlignLeft = true
        player1Widget.left = 140
        player1Widget.isAlignTop = true
        player1Widget.top = 280

        const leftButtonNode = createUINode()
        leftButtonNode.setParent(content)
        const leftButtonWidget = leftButtonNode.addComponent(Widget)
        leftButtonWidget.isAlignTop = true
        leftButtonWidget.top = 0
        leftButtonWidget.isAlignLeft = true
        leftButtonWidget.left = 0
        const leftButtonTransform = leftButtonNode.getComponent(UITransform)
        leftButtonTransform.setContentSize(410, 249)
        const leftButtonSprite = leftButtonNode.addComponent(Sprite)
        leftButtonSprite.sizeMode = Sprite.SizeMode.CUSTOM
        const leftButton = leftButtonNode.addComponent(Button)
        const leftClickEventHandler = new EventHandler();
        leftClickEventHandler.target = this.node.parent;
        leftClickEventHandler.component = manager;
        leftClickEventHandler.handler = 'selectPerson';
        leftClickEventHandler.customEventData = "singlePerson";
        leftButton.clickEvents.push(leftClickEventHandler)

        let player2 = createUINode("player2")
        player2.setParent(content)
        createUILabel({ parentNode: player2, text: '电脑玩家2' })
        const player2Widget = player2.addComponent(Widget)
        player2Widget.isAlignRight = true
        player2Widget.right = 140
        player2Widget.isAlignTop = true
        player2Widget.top = 280

        const rightButtonNode = createUINode()
        rightButtonNode.setParent(content)
        const rightButtonWidget = rightButtonNode.addComponent(Widget)
        rightButtonWidget.isAlignTop = true
        rightButtonWidget.top = 0
        rightButtonWidget.isAlignRight = true
        rightButtonWidget.right = 0
        const rightButtonTransform = rightButtonNode.getComponent(UITransform)
        rightButtonTransform.setContentSize(410, 249)
        const rightButtonSprite = rightButtonNode.addComponent(Sprite)
        rightButtonSprite.sizeMode = Sprite.SizeMode.CUSTOM
        const rightButton = rightButtonNode.addComponent(Button)
        const clickEventHandler = new EventHandler();
        clickEventHandler.target = this.node.parent; // 这个 node 节点是你的事件处理代码组件所属的节点
        clickEventHandler.component = manager;// 这个是脚本类名
        clickEventHandler.handler = 'selectPerson';
        clickEventHandler.customEventData = "doublePerson";
        rightButton.clickEvents.push(clickEventHandler)
    }
    // 设置双人的动画状态
    setSinglePersonStatus(color = DataManager.Instance.color, play: Boolean = true) {
        let node = this.playGameNode.getChildByName('singlePerson')
        let label = node.getChildByName('personLabel')?.getComponent(Label)
        label.color = new math.Color(color)
        let personSpriteNode = node.getChildByName('personSpriteNode')
        let animation = personSpriteNode.getComponent(Animation)
        play ? animation.play() : animation.pause()
    }
    // 设置双人的动画状态
    setDoublePersonStatus(color = DataManager.Instance.color, play: Boolean = true) {
        let node = this.playGameNode.getChildByName('doublePerson')
        let label = node.getChildByName('personLabel')?.getComponent(Label)
        label.color = new math.Color(color)
        let personSpriteNode = node.getChildByName('personSpriteNode')
        let animation = personSpriteNode.getComponent(Animation)
        play ? animation.play() : animation.pause()
        let personSpriteNode1 = node.getChildByName('personSpriteNode1')
        let animation1 = personSpriteNode1.getComponent(Animation)
        play ? animation1.play() : animation1.pause()
    }
    // 创建选择关卡弹框
    createdLevelChange(mamager = "homeManager", content, level_list, room: any = {}, maskBox = null,) {
        let param = chunkArray(level_list, 10)
        let spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, `692.png`).spriteFrame
        const levelNode = createUINode('levelNode')
        levelNode.setParent(content)
        const size = 70
        param.forEach((item, index) => {
            item.forEach((item1, index1) => {
                let children = createUINode(`levelChildren${item1.id}`)
                children.setParent(levelNode)
                const transform = children.getComponent(UITransform)
                transform.setContentSize(size, size)
                const sprite = children.addComponent(Sprite)
                sprite.sizeMode = Sprite.SizeMode.CUSTOM
                sprite.spriteFrame = spriteFrame
                const widget = children.addComponent(Widget)
                widget.isAlignTop = true
                widget.top = -100 + (index * (size + 10))
                widget.isAlignLeft = true
                widget.left = -345 + (index1 * (size + 10))
                let labelNode = createUINode('labelNode')
                labelNode.setParent(children)
                let text = ''
                if (item1.type == 1) {
                    text = '试'
                } else {
                    text = item1.levels.length != 0 ? item1.orderNum + '' : '?'
                }
                createUILabel({ parentNode: labelNode, text, color: maskBox == null ? DataManager.Instance.color : '#999' })
                if (room.ownerId == userStore().info?.id || !maskBox) {
                    const button = children.addComponent(Button)
                    const eventHandler = new EventHandler();
                    eventHandler.target = this.node.parent;
                    eventHandler.component = mamager;
                    eventHandler.handler = maskBox == null ? 'determineLevels' : 'avenueLevels';
                    eventHandler.customEventData = item1.id;
                    button.duration = .1
                    button.zoomScale = 0.95
                    button.transition = Button.Transition.SCALE
                    button.clickEvents.push(eventHandler)
                }
            })
        })
        if (maskBox) {
            let topNode = createUINode()
            topNode.setParent(content)
            const topWidget = topNode.addComponent(Widget)
            topWidget.isAlignTop = true
            topWidget.top = 0
            createUILabel({ parentNode: topNode, text: "联机", fontSize: 28 })
            this.createDoubleSingle(topNode)
            const revertNode = createUINode("revertNode")
            revertNode.setParent(maskBox)
            let text = `等待${room.ownerNickname}下一步操作`
            console.log(room.ownerId == userStore().info?.id)
            if (room.ownerId == userStore().info?.id) {
                const button = revertNode.addComponent(Button)
                const clickEventHandler = new EventHandler();
                clickEventHandler.target = this.node.parent; // 这个 node 节点是你的事件处理代码组件所属的节点
                clickEventHandler.component = mamager;// 这个是脚本类名
                clickEventHandler.handler = 'startGame';
                clickEventHandler.customEventData = '';
                button.duration = .1
                button.zoomScale = 0.95
                button.transition = Button.Transition.SCALE
                button.clickEvents.push(clickEventHandler)
                text = "开始游戏"
            }
            createUILabel({ parentNode: revertNode, text })
            const revertWidget = revertNode.addComponent(Widget)
            revertWidget.isAlignBottom = true
            revertWidget.bottom = 30
            revertWidget.isAlignHorizontalCenter = true
        }
    }
    createDoubleSingle(topNode) {
        const singleNode = createUINode()
        singleNode.setParent(topNode)
        const singleWidget = singleNode.addComponent(Widget)
        singleWidget.isAlignTop = true
        singleWidget.top = 60
        singleWidget.isAlignLeft = true
        singleWidget.left = -15
        const transform = singleNode.getComponent(UITransform)
        transform.setContentSize(50, 50)
        const singleSprite = singleNode.addComponent(Sprite)
        singleSprite.sizeMode = Sprite.SizeMode.CUSTOM
        singleSprite.spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, `502.png`).spriteFrame

        const singleNode1 = createUINode()
        singleNode1.setParent(topNode)
        const singleWidget1 = singleNode1.addComponent(Widget)
        singleWidget1.isAlignTop = true
        singleWidget1.top = 60
        singleWidget1.isAlignLeft = true
        singleWidget1.left = 35
        const transform1 = singleNode1.getComponent(UITransform)
        transform1.setContentSize(50, 50)
        const singleSprite1 = singleNode1.addComponent(Sprite)
        singleSprite1.sizeMode = Sprite.SizeMode.CUSTOM
        singleSprite1.spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, `504.png`).spriteFrame
    }
    // 创建游戏记录
    setCreateRecord(level: LevelInfo, manager = "other", playerId = null) {
        console.log(userStore().info)
        createRecord({
            levelId: level.id,
            playerId: playerId ? playerId : userStore().info?.id,
            mode: DataManager.Instance.gameMode,
            roomId: DataManager.Instance.room?.id,
            secondPlayerId: DataManager.Instance.room?.memberId,
        }).then(res => {
            DataManager.Instance.record_id = res.record.id
            res.levels =
                DataManager.Instance.levelInfo = { ...level, levels: JSON.parse(res.levels) }
            if (manager == "other") {
                director.loadScene('game')
            }
        }).catch(err => {
            console.log(err.message)
            showToast(err.message)
        })
    }
    // 修改游戏记录
    updateCreateRecord(level: LevelInfo, status: number, playerId = null,) {
        if(!DataManager.Instance.record_id) return
        updateRecord({
            id: DataManager.Instance.record_id,
            levelId: level.id,
            nextLevel: level.nextLevel,
            playerId: playerId ? playerId : userStore().info?.id,
            mode: DataManager.Instance.gameMode,
            roomId: DataManager.Instance.room?.id,
            secondPlayerId: DataManager.Instance.room?.memberId,
            status,
            fraction: DataManager.Instance.fraction
        }).then(res => {
            // 状态修改成功
            console.log('状态修改成功')
        }).catch(err => {
            console.log(err.message)
            showToast(err.message)
        })
    }
    async selectLevel(controllerManager, level_list, manager = "homeManager") {
        let { content } = await controllerManager.showDrawerContent({ name: 'selectLevel', tips: "关卡选择" })
        await controllerManager.close('gameType')
        let topNode = createUINode()
        topNode.setParent(content)
        const topWidget = topNode.addComponent(Widget)
        topWidget.isAlignTop = true
        topWidget.top = 0
        if (DataManager.Instance.gameMode == GAME_MODE_ENUM.SINGLE) {
            createUILabel({ parentNode: topNode, text: "单人", fontSize: 28 })
            const singleNode = createUINode()
            singleNode.setParent(topNode)
            const singleWidget = singleNode.addComponent(Widget)
            singleWidget.isAlignTop = true
            singleWidget.top = 60
            const transform = singleNode.getComponent(UITransform)
            transform.setContentSize(50, 50)
            const singleSprite = singleNode.addComponent(Sprite)
            singleSprite.sizeMode = Sprite.SizeMode.CUSTOM
            singleSprite.spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, `${502}.png`).spriteFrame //single.find(item => item.name == '502')
        } else {
            if (DataManager.Instance.gameMode == GAME_MODE_ENUM.DOUBLE) {
                createUILabel({ parentNode: topNode, text: "双人", fontSize: 28 })
            } else {
                createUILabel({ parentNode: topNode, text: "联机", fontSize: 28 })
            }
            this.createDoubleSingle(topNode)
        }
        this.createdLevelChange(manager, content, level_list,)
    }
}


